#include "guiterm.hpp"

TabMenu::TabMenu(TerminalWindow *window)
	:QMenu(tr("Tabs"))
{
	this->window = window;
	this->mapper = NULL;
	
	// Bind Ctrl+A to the tabs menu (like in GNU screen)
	QShortcut *openTabMenuShortcut = new QShortcut(QKeySequence("Ctrl+a"), this);
	connect(openTabMenuShortcut, SIGNAL(activated()), window, SLOT(openTabMenu()));
	
	connect(this, SIGNAL(aboutToShow()), this, SLOT(fillMenu()));
}

TabMenu::~TabMenu()
{
	delete createTabAct;
	delete nextTabAct;
	delete prevTabAct;
	delete lastTabAct;
	delete mapper;
	deleteTabSwitchActions();
}

void TabMenu::fillMenu()
{
	deleteTabSwitchActions();
	
	clear();
	
	// Standard actions for creating and switching tabs
	createTabAct = new QAction(tr("&Create tab"), this);
	createTabAct->setShortcut(QKeySequence(Qt::CTRL+Qt::Key_A, Qt::Key_C));
	connect(createTabAct, SIGNAL(triggered()), window, SLOT(createTab()));
	
	nextTabAct = new QAction(tr("&Next tab"), this);
	nextTabAct->setShortcut(QKeySequence(Qt::CTRL+Qt::Key_A, Qt::Key_N));
	connect(nextTabAct, SIGNAL(triggered()), window, SLOT(nextTab()));
	
	prevTabAct = new QAction(tr("&Prev tab"), this);
	prevTabAct->setShortcut(QKeySequence(Qt::CTRL+Qt::Key_A, Qt::Key_P));
	connect(prevTabAct, SIGNAL(triggered()), window, SLOT(prevTab()));
	
	lastTabAct = new QAction(tr("L&ast tab"), this);
	lastTabAct->setShortcut(QKeySequence(Qt::CTRL+Qt::Key_A, Qt::Key_A));
	connect(lastTabAct, SIGNAL(triggered()), window, SLOT(lastTab()));
	
	addAction(createTabAct);
	addAction(nextTabAct);
	addAction(prevTabAct);
	addAction(lastTabAct);
	
	addSeparator();
	
	mapper = new QSignalMapper(this);
	connect(mapper, SIGNAL(mapped(int)), window, SLOT(changeTab(int)));
	
	vector<Tab*> tabs = window->getTabs();
	for(size_t ii=0; ii<tabs.size(); ii++)
	{
		int index = tabs[ii]->getIndex();
		string name = tabs[ii]->getName();
		
		string menuText = retprintf("Switch to tab %s%i (%s)",
			(index<10)?"&":"",
			index, name.c_str());
		QAction *action = new QAction(menuText.c_str(), this);
		if(index<10)
			action->setShortcut(QKeySequence(Qt::CTRL+Qt::Key_A, (Qt::Key_0+index)));
		action->setData(index);
		
		mapper->setMapping(action, index);
		connect(action, SIGNAL(triggered()), mapper, SLOT(map()));
		addAction(action);
	}
}

void TabMenu::deleteTabSwitchActions()
{
	if(mapper) {
		delete mapper;
		mapper = NULL;
	}
	for(size_t ii=0; ii<tabSwitchActions.size(); ii++)
		delete tabSwitchActions[ii];
	tabSwitchActions.clear();
}

